import {
  AddUser,
  DelUser,
  GetUserByPage,
  loadTransferUserRelRoler,
  LockUser,
  saveRolesByUserId,
  updatePassword,
  updateUser,
  GetUserInfo,
  ReLogin,
} from '@/services/system/user';
import { customerList } from '@/services/sales/license';
import { getAllCustomer } from '@/services/system/customer';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Select, Switch, Transfer } from 'antd';
import type { TransferDirection } from 'antd/es/transfer';
import React, { useEffect, useReducer, useRef, useState } from 'react';
import { roleFormInit, roleFormReducer, userFormInit, userFormReducer } from './userReducer';
import DebounceSelect from '@/components/DebounceSelect';
import { history, useModel } from 'umi';
const { Option } = Select;

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

async function fetchUserList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return customerList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  });
}
const User: React.FC<{}> = () => {
  // 表单弹框信息
  const [userFormState, userdispatch] = useReducer(userFormReducer, userFormInit);

  // 绑定角色信息弹框
  const [roleFormState, roledispatch] = useReducer(roleFormReducer, roleFormInit);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [value, setValue] = useState<UserValue[]>([]);

  const [formVisit, setFormVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('重置密码'); // 标题
  const [confirmLoading3, setConfirmLoading3] = useState(false); //加载

  // 绑定客户信息
  const [customerData, setCustomerData] = useState<object[]>([{ id: '', name: '' }]);

  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const { initialState, setInitialState } = useModel('@@initialState');
  const onChange = (nextTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
    roledispatch({ type: 'onchange', targetKeys: nextTargetKeys });
  };

  // const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
  //   console.log('sourceSelectedKeys:', sourceSelectedKeys);
  //   console.log('targetSelectedKeys:', targetSelectedKeys);
  //   setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  // };

  const onScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement>) => {
    console.log('direction:', direction);
    console.log('target:', e.target);
  };

  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await getAllCustomer({});
      setCustomerData(result?.data);
    })();
  }, []);

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '用户名', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '客户名称', //表头显示的名称

      dataIndex: 'customerName',
    },

    // {
    //   title: '客户名称', //表头显示的名称
    //   hideInTable: true,
    //   dataIndex: 'customerName',
    // },
    // {
    //   title: '昵称', //表头显示的名称
    //   search: false,
    //   dataIndex: 'nickName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    // },
    {
      title: '性别', //表头显示的名称
      search: false,
      dataIndex: 'gender', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      valueEnum: {
        0: '男',
        1: '女',
      },
    },
    {
      title: '电话', //表头显示的名称
      search: false,
      dataIndex: 'phone', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '邮箱', //表头显示的名称
      search: false,
      dataIndex: 'email', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '状态', //表头显示的名称
      search: false,
      dataIndex: 'isLocked', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      render: (text, record, index, action) => (
        <Switch
          checked={text ? true : false}
          onChange={async (checked: boolean) => {
            console.log(text, record, '---checked---');
            const arg = {
              id: record.id,
              isLocked: checked ? 1 : 0,
            };
            await LockUser(arg);
            action?.reload();
          }}
        />
      ),
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            userdispatch({ type: 'update' });
            form.setFieldsValue({
              name: record.name,
              id: record.id,
              email: record.email,
              phone: record.phone,
              gender: record.gender,
              customerId: { label: record.customerName, value: record.customerId },
            });
          }}
        >
          编辑
        </a>,
        <a
          key="updatePassword"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            setFormVisit(true);
            form2.setFieldsValue({
              name: record.name,
              id: record.id,
              customerId: record.customerId,
            });
          }}
        >
          重置密码
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            roledispatch({ type: 'setUserId', userId: record.id });
            // actionRef.current.reload();
            // setDeleteVisit(true);
            Modal.confirm({
              title: '删除用户',
              content: '确定要删除用户吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await DelUser({ id: record.id });
                actionRef.current.reload();
              },
            });

            // actionRef.current.reload();
          }}
        >
          删除
        </a>,

        <a
          key="linkRole"
          onClick={async () => {
            roledispatch({ type: 'open', userId: record.id });
            const result = await loadTransferUserRelRoler({ id: record.id });
            roledispatch({
              type: 'loadData',
              rolesData: result?.data.data,
              targetKeys: result?.data.value,
            });
            actionRef.current.reload();
            // actionRef.current.reload();
          }}
        >
          绑定角色
        </a>,

        <a
          key="reLoin"
          onClick={async () => {
            const tokenMsg = await ReLogin({ name: record.name });
            sessionStorage.setItem('bctoken', JSON.stringify(tokenMsg.data));
            const result = await GetUserInfo();
            const currentUser = result?.data; //获取用户信息;必须要要获取用户信息
            const roleInfo = currentUser.roleInfos || [];
            const permissions = currentUser.permissionInfos || [];
            debugger;
            // actionRef.current.reload();
            //设置
            await setInitialState((s) => ({
              ...s,
              currentUser: currentUser,
              roleInfo: roleInfo,
              permissions: permissions,
            }));

            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            window.location.href = redirect || '/welcome';
          }}
        >
          登录
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (userFormState.title == '新建用户') {
      const result = await AddUser(form.getFieldsValue());
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      if (typeof form.getFieldValue('customerId') == 'string') {
        await updateUser(form.getFieldsValue());
      } else {
        await updateUser({
          customerId: form.getFieldsValue().customerId.value,
          email: form.getFieldsValue().email,
          gender: form.getFieldsValue().gender,
          id: form.getFieldsValue().id,
          name: form.getFieldsValue().name,
          password: form.getFieldsValue().password,
          phone: form.getFieldsValue().phone,
        });
      }
    }
    setConfirmLoading(false);
    userdispatch({ type: 'close' });
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    setConfirmLoading3(true);
    await updatePassword(form2.getFieldsValue());
    setConfirmLoading3(false);
    setFormVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const onGenderChange = (value: string) => {};

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="用户查询" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              // console.log(selectedRows, '---选取多行----');
              // 1.清空form
              userdispatch({ type: 'create' });

              form.resetFields();
              //
            }}
            type="primary"
          >
            新建用户
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const result = await GetUserByPage(params);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        scroll={{ x: 1600 }}
        columns={columns} //上面定义的
        rowSelection={{}}
      />
      <Modal
        title={userFormState.title}
        visible={userFormState.visit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => userdispatch({ type: 'close' })}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="用户名"
            name="name"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input disabled={userFormState.createOrUpdate} />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            hidden={userFormState.createOrUpdate}
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item name={'email'} label="邮箱" rules={[{ type: 'email' }]}>
            <Input />
          </Form.Item>
          <Form.Item name={'phone'} label="电话">
            <Input />
          </Form.Item>

          <Form.Item name={'gender'} label="性别">
            <Select>
              <Option value="0">男</Option>
              <Option value="1">女</Option>
            </Select>
          </Form.Item>

          <Form.Item label="客户信息" name="customerId">
            {/* <Select
              placeholder="Select a option and change input text above"
              onChange={onGenderChange}
              allowClear
            >
              {customerData.map((item) => (
                <Option key={item.id}>{item.name}</Option>
              ))}
            </Select> */}
            <DebounceSelect
              showSearch
              value={value}
              placeholder="Select a option and change input text above"
              fetchOptions={fetchUserList}
              onChange={(newValue) => {
                setValue(newValue as UserValue[]);
              }}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={formTitle}
        visible={formVisit}
        onOk={handleSubmit2}
        confirmLoading={confirmLoading3}
        onCancel={() => {
          setFormVisit(false);
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form2}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="绑定角色"
        visible={roleFormState.visit}
        confirmLoading={confirmLoading2}
        onOk={async () => {
          setConfirmLoading2(true);
          await saveRolesByUserId({
            userId: roleFormState.userData.id,
            rolesId: roleFormState.targetKeys,
          });
          actionRef.current.reload();
          setConfirmLoading2(false);
          roledispatch({ type: 'close' });
        }}
        onCancel={() => {
          roledispatch({ type: 'close' });
        }}
      >
        <Transfer
          dataSource={roleFormState.rolesData}
          titles={['未选', '已经']}
          targetKeys={roleFormState.targetKeys}
          onChange={onChange}
          onScroll={onScroll}
          render={(item) => item.title}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default User;
